<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog" top="10vh" width="55%">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :model="formData"
             :rules="formRules"
             label-width="auto"
             :inline="true"
             status-icon>

      <el-row class="panel-group" :gutter="8" style="margin-bottom: 1rem;">
        <el-alert v-if="calculateCountData" title="时间范围" type="error" :closable="false" style="margin-bottom: 8px;">
          <template #title>
            <span>时间范围：{{ calculateCountData.time }}</span>
          </template>
        </el-alert>

        <el-col :md="8" :sm="12" class="card-panel-col">
          <card-panel :decimals="2"
                      :model-value="calculateCountData.payment"
                      icon-class="money"
                      icon-style="style1"
                      panel-text="现金支付总额">
          </card-panel>
        </el-col>

        <el-col :md="8" :sm="12" class="card-panel-col">
          <card-panel :decimals="0"
                      :model-value="calculateCountData.count_user"
                      icon-class="ribbon"
                      icon-style="style2"
                      panel-text="预估红包数 - 用户">
          </card-panel>
        </el-col>

        <el-col :md="8" :sm="12" class="card-panel-col">
          <card-panel :decimals="0"
                      :model-value="calculateCountData.count_shop"
                      icon-class="storefront"
                      icon-style="style3"
                      panel-text="预估红包数 - 商户">
          </card-panel>
        </el-col>
      </el-row>

      <el-form-item label="红包类型：" prop="type" style="width:98%;max-width: unset">
        <DictSelectV2 v-model="formData.type" dict-type="subsidy_packet_type"/>
      </el-form-item>

      <el-form-item label="红包标题：" prop="title" style="width:98%;max-width: unset">
        <el-input v-model="formData.title" maxlength="128" placeholder="请输入红包标题" show-word-limit/>
      </el-form-item>

      <el-form-item label="红包数量：" prop="quantity">
        <el-input-number v-model="formData.quantity" :min="1" :step="1" controls-position="right" placeholder="请输入红包数量"/>
      </el-form-item>

      <el-form-item label="红包金额：" prop="amount">
        <el-input-number v-model="formData.amount" :precision="2" :min="0.01" :step="1" controls-position="right" placeholder="请输入红包金额"/>
      </el-form-item>

      <el-form-item label="最小金额：" prop="min_amount" v-form-item-tip="'单个红包最小金额'">
        <el-input-number v-model="formData.min_amount" :precision="2" :min="0.01" :step="0.1" controls-position="right" placeholder="请输入最小金额"/>
      </el-form-item>

      <el-form-item label="最小范围：" prop="scope_ratio_min" v-form-item-tip="'红包数量很大且红包金额很小时，请将该值改大'">
        <el-input-number v-model="formData.scope_ratio_min" :precision="2" :min="0.01" :max="1.0" :step="0.01" controls-position="right" placeholder="请输入最小范围"/>
        <span v-if="formData.scope_ratio_min != undefined" class="tip">{{ toPercent(formData.scope_ratio_min) }}</span>
      </el-form-item>

      <el-form-item label="最大范围：" prop="scope_ratio_max" v-form-item-tip="'红包数量很大且红包金额很小时，请将该值改小'">
        <el-input-number v-model="formData.scope_ratio_max" :precision="2" :min="1.0" :step="0.01" controls-position="right" placeholder="请输入最大范围"/>
        <span v-if="formData.scope_ratio_max != undefined" class="tip">{{ toPercent(formData.scope_ratio_max) }}</span>
      </el-form-item>

      <el-form-item label="启用状态：" prop="enabled" v-form-item-tip="'红包是否启用/停用'">
        <el-radio-group v-model="formData.enabled">
          <el-radio-button :value="true">启用</el-radio-button>
          <el-radio-button :value="false">停用</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-alert v-if="estimateMaxAmount > 0" title="预估最大红包金额" type="info" :closable="false">
        <template #title>
          <span>预估最大红包金额：{{ toDecimal(estimateMaxAmount, 2) }}</span>
        </template>
      </el-alert>
    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-permission="['subsidy:packet:operations']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { subsidyPacketCalculateCount, subsidyPacketSend } from '@/api/api-subsidy.ts';
import { DictSelectV2 } from '@/components/dict-select';
import { CardPanel } from '@/components/other';
import { toDecimal, toPercent } from '@/utils';

defineOptions({name: 'queue-subsidy-packet-send-form'})

const formRef = ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

export type PacketSendParams = {
  type: number;
  title: string;
  quantity: number;
  amount: number;
  min_amount: number;
  scope_ratio_min: number;
  scope_ratio_max: number;
  enabled: boolean;
};
/** 默认表单数据 */
const defaultForm: PacketSendParams = <PacketSendParams>{type: 0, enabled: false, min_amount: 0.10, scope_ratio_min: 0.80, scope_ratio_max: 1.60};

// 表单数据
const formData = ref({...defaultForm});

// 表单验证规则
const formRules = reactive<FormRules>({
  type: [{required: true, message: '类型不能为空', trigger: 'blur'}],
  title: [{required: true, message: '标题不能为空', trigger: 'blur'}],
  quantity: [{required: true, message: '数量不能为空', trigger: 'blur'}],
  amount: [{required: true, message: '金额不能为空', trigger: 'blur'}],
  min_amount: [{required: true, message: '最小金额不能为空', trigger: 'blur'}],
  scope_ratio_min: [{required: true, message: '最小范围不能为空', trigger: 'blur'}],
  scope_ratio_max: [{required: true, message: '最大范围不能为空', trigger: 'blur'}],
  enabled: [{required: true, message: '启用状态不能为空', trigger: 'blur'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

const calculateCountData = reactive({
  time: '',
  payment: 0,
  count_user: 0,
  count_shop: 0,
});

/** 打开弹窗 */
const open = async () => {
  dialogMode.value = 1;
  dialogTitle.value = '发红包';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();

  // 加载用户数据
  const {data} = await subsidyPacketCalculateCount()
  calculateCountData.time = data.time;
  calculateCountData.payment = data.payment;
  calculateCountData.count_user = data.count_user;
  calculateCountData.count_shop = data.count_shop;
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    subsidyPacketSend(formData.value).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())

  });
};

/** 重置表单 */
const handleFormReset = () => {
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

const estimateMaxAmount = computed(() => {
  if (formData.value.quantity && formData.value.amount && formData.value.min_amount && formData.value.scope_ratio_max) {
    if (formData.value.quantity == 1) {
      return formData.value.amount;
    }
    // 总计最小红包金额
    let min_amount_total = formData.value.min_amount * formData.value.quantity;
    // 剩余待处理金额
    let surplus_amount = formData.value.amount - min_amount_total;
    // 平均最大红包金额
    return (surplus_amount / formData.value.quantity) * formData.value.scope_ratio_max;
  }
  return 0.00;
});

</script>

<style lang="scss" scoped>
.form-dialog {
  .el-select {
    width: 200px;
  }

  .el-input-number {
    width: 160px;
  }

  .el-form--inline .el-form-item {
    width: 350px;
  }
}
</style>
